package com.shfl.Controller;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;

import com.shfl.Util.ExcelUtil;
import com.shfl.Util.MapObjUtil;
import com.shfl.Util.POIUtil;
import com.shfl.app.One;
import com.shfl.app.Second;
import com.shfl.app.Three;
import com.shfl.model.WokingFinishing;
import com.shfl.model.WokingLog;
import com.shfl.stock.Stock;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;

@SuppressWarnings("unchecked")
public class SecondController implements Initializable {

	@FXML
	private Button selestFile;

	@FXML
	private TextField selectPath;

	@FXML
	private TableView tview;

	@FXML
	private TableColumn userName;

	@FXML
	private TableColumn c1;

	@FXML
	private TableColumn c2;

	@FXML
	private TableColumn c3;

	@FXML
	private TableColumn c4;

	@FXML
	private TableColumn c5;

	@FXML
	private TableColumn c6;

	@FXML
	private TableColumn c7;

	@FXML
	private TableColumn c8;

	@FXML
	private TableColumn c9;

	@FXML
	private TableColumn c10;

	@FXML
	private TableColumn c11;

	@FXML
	private TableColumn c12;

	@FXML
	private TableColumn c13;

	@FXML
	private TableColumn c14;

	@FXML
	private TableColumn c15;

	@FXML
	private TableColumn c16;

	@FXML
	private TableColumn c17;

	@FXML
	private TableColumn c18;

	@FXML
	private TableColumn c19;

	@FXML
	private TableColumn c20;

	@FXML
	private TableColumn c21;

	@FXML
	private TableColumn c22;

	@FXML
	private TableColumn c23;

	@FXML
	private TableColumn c24;

	@FXML
	private TableColumn c25;

	@FXML
	private TableColumn c26;

	@FXML
	private TableColumn c27;

	@FXML
	private TableColumn c28;

	@FXML
	private TableColumn c29;

	@FXML
	private TableColumn c30;

	@FXML
	private TableColumn c31;

	@FXML
	private Button firstStep;// 下一步

	@FXML
	private Button selectButton;// 查询按钮

	@FXML
	private Button selectExport;// 选择导出的路径

	@FXML
	private TextField selectExportPath;// 导出的路劲

	@FXML
	private TextField selectInput;
	
	@FXML
	private Button breakOne;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		// 选择文件
		this.selestFile.setOnAction(event -> {
			Stock.SECOND_STAG_DIALOG.activateProgressBar();
			FileChooser fileChooser = new FileChooser();
			// 只能够获取的文件
			fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XLSX", "*.xlsx"),
					new FileChooser.ExtensionFilter("XLS", "*.xls"));
			Window window = ((Node) event.getSource()).getScene().getWindow();
			File file = fileChooser.showOpenDialog(window);
			if (file != null) {
				
				this.selectPath.setText(file.getAbsolutePath());
				List<String[]> list = new ArrayList<String[]>();
				try {
					list = POIUtil.readExcel(file);

				} catch (IOException e) {
					Stock.SECOND_STAG_DIALOG.cancelProgressBar();
					e.printStackTrace();
				}finally {
					Stock.SECOND_STAG_DIALOG.cancelProgressBar();
				}
				insertUserWorking(list);
				insertWokingFinishing();
				insertTableView();
			}
			Stock.SECOND_STAG_DIALOG.cancelProgressBar();
		});
		// 第一步
		this.firstStep.setOnAction(event -> {
			if(Stock.WOKING_FINISHING_LIST.size() == 0 || Stock.USER_INFO.isEmpty()){
				return ;
			}
			try {
				changeWindow();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});

		// 查询
		this.selectButton.setOnAction(event -> {
			List<WokingFinishing> wokingLogList = new LinkedList<WokingFinishing>();
			getTableView(wokingLogList);
			String userName = this.selectInput.getText();
			if (userName.trim().isEmpty()) {
				insertTableView();
			} else {
				Optional<WokingFinishing> wokingFinishing = Stock.WOKING_FINISHING_LIST.stream()
						.filter(s -> s.getUserName().equals(userName.trim())).findFirst();
				if (wokingFinishing.isPresent()) {
					wokingLogList.add(wokingFinishing.get());
					getTableView(wokingLogList);
				}
			}
		});
		// 选择导出路径
		this.selectExport.setOnAction(event -> {
			List<Map<String, Object>> tempList = new LinkedList<Map<String, Object>>();
			String userName = this.selectInput.getText();
			if (userName.trim().isEmpty()) {
				for (WokingFinishing wokingFinishing : Stock.WOKING_FINISHING_LIST) {
					tempList.add(MapObjUtil.object2Map(wokingFinishing));
				}
			} else {
				Optional<WokingFinishing> wokingFinishing = Stock.WOKING_FINISHING_LIST.stream()
						.filter(s -> s.getUserName().equals(userName.trim())).findFirst();
				if (wokingFinishing.isPresent()) {
					tempList.add(MapObjUtil.object2Map(wokingFinishing.get()));
				}
			}
			DirectoryChooser chooser = new DirectoryChooser();
			Window window = ((Node) event.getSource()).getScene().getWindow();
			File file = chooser.showDialog(window);
			if (file != null && file.exists() && file.isDirectory()) {
				this.selectExportPath.setText(file.getAbsolutePath());
				// List dataKey
				String[] dataKeyArry = { "userName", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "c10", "c11",
						"c12", "c13", "c14", "c15", "c16", "c17", "c18", "c19", "c20", "c21", "c22", "c23", "c24",
						"c25", "c26", "c27", "c28", "c29", "c30", "c31" };
				// List dataTitle
				String[] dataTitleArry = { "员工姓名", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
						"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29",
						"30", "31" };
				Stock.SECOND_STAG_DIALOG.activateProgressBar();
				// 生成Excel
				try{
					Map rMap = ExcelUtil.buildExcel(file.getAbsolutePath(), Arrays.asList(dataKeyArry),
							Arrays.asList(dataTitleArry), tempList, "员工考勤整理");
				}catch (Exception e) {
					Stock.SECOND_STAG_DIALOG.cancelProgressBar();
				}
				
				Stock.SECOND_STAG_DIALOG.cancelProgressBar();
			}

		});

		this.breakOne.setOnAction(event -> {
			try {
				breakWindow();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		});
	}

	public void insertUserWorking(List<String[]> list) {
		Stock.USER_WORKING_LOG = new HashMap<String, List<WokingLog>>();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
		WokingLog wokingLog = null;
		List<WokingLog> wokingLogList = null;
		for (String[] str : list) {
			if (str.length == 3) {
				if (!Stock.USER_WORKING_LOG.containsKey(str[1])) {
					wokingLog = new WokingLog();
					String[] wokingDateTime = str[2].split(" ");
					if (wokingDateTime.length == 2) {
						String date = wokingDateTime[0];
						String time = wokingDateTime[1];
						if (date.split("-").length == 3) {
							String day = date.split("-")[2];
							wokingLog.setWorkingDate(Integer.valueOf(day));
							wokingLog.setClockIn(time);
							wokingLogList = new LinkedList<WokingLog>();
							wokingLogList.add(wokingLog);
							Stock.USER_WORKING_LOG.put(str[1], wokingLogList);
						}
					}
				} else {
					wokingLogList = Stock.USER_WORKING_LOG.get(str[1]);
					String[] wokingDateTime = str[2].split(" ");
					if (wokingDateTime.length == 2) {
						String date = wokingDateTime[0];
						String time = wokingDateTime[1];
						if (date.split("-").length == 3) {
							String day = date.split("-")[2];
							int i = Integer.valueOf(day);
							if(time.startsWith("00") || time.startsWith("01")){
								i = i - 1;
								day = String.valueOf(i);
							}
							Integer tt = i;
							
							Optional<WokingLog> WokingLogOp = wokingLogList.stream()
									.filter(s -> s.getWorkingDate().equals(tt)).findFirst();
							if (WokingLogOp.isPresent()) {
								wokingLog = WokingLogOp.get();
								String clockInTemp = wokingLog.getClockIn();
								Long userStratTime = 0L;
								Long userEndTime = 0L;
								try {
									userStratTime = simpleDateFormat.parse(clockInTemp).getTime();
									userEndTime = simpleDateFormat.parse(time).getTime();
								} catch (ParseException e) {
									e.printStackTrace();
								}
								if (userStratTime < userEndTime || time.startsWith("00") || time.startsWith("01")) {
									wokingLog.setClockOut(time);
								} else {
									wokingLog.setClockIn(time);
									wokingLog.setClockOut(clockInTemp);
								}
							} else {
								wokingLog = new WokingLog();
								wokingLog.setWorkingDate(Integer.valueOf(day));
								wokingLog.setClockIn(time);
								wokingLogList.add(wokingLog);
								Stock.USER_WORKING_LOG.put(str[1], wokingLogList);
							}
						}
					}
				}
			}
		}
	}

	public void insertTableView() {
		List<WokingFinishing> wokingLogList = new LinkedList<WokingFinishing>();
		getTableView(wokingLogList);
		for (WokingFinishing wokingFinishing : Stock.WOKING_FINISHING_LIST) {
			wokingLogList.add(wokingFinishing);
		}
		getTableView(wokingLogList);
	}

	public void getTableView(List<WokingFinishing> wokingLogList) {
		ObservableList<WokingFinishing> list = FXCollections.observableArrayList();
		userName.setCellValueFactory(new PropertyValueFactory("userName"));// 映射
		c1.setCellValueFactory(new PropertyValueFactory("c1"));

		c2.setCellValueFactory(new PropertyValueFactory("c2"));

		c3.setCellValueFactory(new PropertyValueFactory("c3"));

		c4.setCellValueFactory(new PropertyValueFactory("c4"));

		c5.setCellValueFactory(new PropertyValueFactory("c5"));

		c6.setCellValueFactory(new PropertyValueFactory("c6"));

		c7.setCellValueFactory(new PropertyValueFactory("c7"));

		c8.setCellValueFactory(new PropertyValueFactory("c8"));

		c9.setCellValueFactory(new PropertyValueFactory("c9"));

		c10.setCellValueFactory(new PropertyValueFactory("c10"));

		c11.setCellValueFactory(new PropertyValueFactory("c11"));

		c12.setCellValueFactory(new PropertyValueFactory("c12"));

		c13.setCellValueFactory(new PropertyValueFactory("c13"));

		c14.setCellValueFactory(new PropertyValueFactory("c14"));

		c15.setCellValueFactory(new PropertyValueFactory("c15"));

		c16.setCellValueFactory(new PropertyValueFactory("c16"));

		c17.setCellValueFactory(new PropertyValueFactory("c17"));

		c18.setCellValueFactory(new PropertyValueFactory("c18"));

		c19.setCellValueFactory(new PropertyValueFactory("c19"));

		c20.setCellValueFactory(new PropertyValueFactory("c20"));

		c21.setCellValueFactory(new PropertyValueFactory("c21"));

		c22.setCellValueFactory(new PropertyValueFactory("c22"));

		c23.setCellValueFactory(new PropertyValueFactory("c23"));

		c24.setCellValueFactory(new PropertyValueFactory("c24"));

		c25.setCellValueFactory(new PropertyValueFactory("c25"));

		c26.setCellValueFactory(new PropertyValueFactory("c26"));

		c27.setCellValueFactory(new PropertyValueFactory("c27"));

		c28.setCellValueFactory(new PropertyValueFactory("c28"));

		c29.setCellValueFactory(new PropertyValueFactory("c29"));

		c30.setCellValueFactory(new PropertyValueFactory("c30"));

		c31.setCellValueFactory(new PropertyValueFactory("c31"));
		// list.add(wokingLog); // list添加值对象
		list.addAll(wokingLogList);
		tview.setItems(list); // tableview添加list
	}

	public void insertWokingFinishing() {

		Stock.USER_WORKING_LOG.forEach((k, v) -> {
			WokingFinishing wokingFinishing = new WokingFinishing();
			wokingFinishing.setUserName(k);
			wokingFinishing.setC1(getWokingFinishingValue(v, 1));
			wokingFinishing.setC2(getWokingFinishingValue(v, 2));
			wokingFinishing.setC3(getWokingFinishingValue(v, 3));
			wokingFinishing.setC4(getWokingFinishingValue(v, 4));
			wokingFinishing.setC5(getWokingFinishingValue(v, 5));
			wokingFinishing.setC6(getWokingFinishingValue(v, 6));
			wokingFinishing.setC7(getWokingFinishingValue(v, 7));
			wokingFinishing.setC8(getWokingFinishingValue(v, 8));
			wokingFinishing.setC9(getWokingFinishingValue(v, 9));
			wokingFinishing.setC10(getWokingFinishingValue(v, 10));
			wokingFinishing.setC11(getWokingFinishingValue(v, 11));
			wokingFinishing.setC12(getWokingFinishingValue(v, 12));
			wokingFinishing.setC13(getWokingFinishingValue(v, 13));
			wokingFinishing.setC14(getWokingFinishingValue(v, 14));
			wokingFinishing.setC15(getWokingFinishingValue(v, 15));
			wokingFinishing.setC16(getWokingFinishingValue(v, 16));
			wokingFinishing.setC17(getWokingFinishingValue(v, 17));
			wokingFinishing.setC18(getWokingFinishingValue(v, 18));
			wokingFinishing.setC19(getWokingFinishingValue(v, 19));
			wokingFinishing.setC20(getWokingFinishingValue(v, 20));
			wokingFinishing.setC21(getWokingFinishingValue(v, 21));
			wokingFinishing.setC22(getWokingFinishingValue(v, 22));
			wokingFinishing.setC23(getWokingFinishingValue(v, 23));
			wokingFinishing.setC24(getWokingFinishingValue(v, 24));
			wokingFinishing.setC25(getWokingFinishingValue(v, 25));
			wokingFinishing.setC26(getWokingFinishingValue(v, 26));
			wokingFinishing.setC27(getWokingFinishingValue(v, 27));
			wokingFinishing.setC28(getWokingFinishingValue(v, 28));
			wokingFinishing.setC29(getWokingFinishingValue(v, 29));
			wokingFinishing.setC30(getWokingFinishingValue(v, 30));
			wokingFinishing.setC31(getWokingFinishingValue(v, 31));
			Stock.WOKING_FINISHING_LIST.add(wokingFinishing);
		});

	}

	public String getWokingFinishingValue(List<WokingLog> wokingLogList, int i) {
		Optional<WokingLog> WokingLogOp = wokingLogList.stream().filter(s -> s.getWorkingDate().equals(i)).findFirst();
		if (WokingLogOp.isPresent()) {
			WokingLog wokingLog = WokingLogOp.get();
			return wokingLog.getClockIn() + System.getProperty("line.separator")
					+ ((wokingLog.getClockOut() != null) ? wokingLog.getClockOut() : "");
		}
		return "";
	}

	public void changeWindow() throws Exception {
		Stock.THREE.showWindow();
		Stock.SECOND.stop();
	}
	public void breakWindow() throws Exception {
		Stock.ONE.showWindow();
		Stock.SECOND.stop();
	}
	
}
